<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template v-slot:before>
          <el-button type="primary" size="small" @click="addFn">添加客户</el-button>
        </template>
        <template #after>
          <el-select v-model="selectAgent">
            <el-option label="全部经纪" value="" />
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input v-model="keyword" placeholder="请输入关键字" @change="renderClientList" />
          <el-button @click="search">筛选</el-button>
        </template>
        <template #bottom>
          <!-- 表格 -->
          <el-table :data="clientList" border>
            <el-table-column label="图片" prop="image">
              <template v-slot="{row}">
                <img
                  v-imgerror="require('@/assets/common/bigUserHeader.png')"
                  style="width:100px"
                  :src="row.image"
                  alt=""
                >
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="name" />
            <el-table-column label="邮箱" prop="email" />
            <el-table-column label="电话" prop="phone" />
            <el-table-column label="经纪" prop="agent.name" />
            <el-table-column label="微信" prop="wechat" />
            <el-table-column label="介绍" prop="desc" />
            <el-table-column label="操作">
              <template v-slot="{row}">
                <el-button size="small" type="primary" @click="editFn(row.id)">编辑</el-button>
                <el-button size="small" type="danger" @click="delFn(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #center>
          <!-- 分页器 -->
          <el-row type="flex" justify="center">
            <el-pagination
              layout="prev, pager, next"
              :page-size="pageConfig._limit"
              :current-page.sync="currentPage"
              :total="total"
              @current-change="currentChange"
            />
          </el-row>
        </template>
      </PageTools>

      <!-- 弹窗 -->
      <el-dialog :title="formData.id?'编辑角色':'新增角色'" :visible="showDialog" @close="closeFn">
        <el-form ref="form" :rules="rules" :model="formData" label-width="120px">
          <el-form-item label="经纪" prop="agent">
            <el-select v-model="formData.agent">
              <el-option
                v-for="item in agentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" style="width:80%" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" style="width:80%" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="formData.phone" style="width:80%" placeholder="请输入电话" />
          </el-form-item>
          <el-form-item label="微信" prop="wechat">
            <el-input v-model="formData.wechat" style="width:80%" placeholder="请输入微信" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="formData.desc" style="width:80%" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="封面" prop="image">
            <ImageUpload ref="upload" />
            <el-input style="width:80%" placeholder="强制设置图片跳过上传" />
          </el-form-item>
        </el-form>
        <!-- 弹窗点击按钮 -->
        <template v-slot:footer>
          <el-row type="flex" justify="center">
            <el-col :span="6">
              <el-button type="primary" size="small" @click="confirmFn">确定</el-button>
              <el-button size="small" @click="closeFn">取消</el-button>
            </el-col>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getClientList, addClient, delClient, getClientById, updateClient, getClientNumber } from '@/api/customer'
import { getAgentList } from '@/api/property'
export default {
  data() {
    return {
      keyword: '',
      selectAgent: '',
      showDialog: false,
      clientList: [],
      total: 0,
      currentPage: 1,
      formData: {
        agent: '',
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '',
        image: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      },
      pageConfig: {
        _limit: 2,
        _start: 0
      },
      agentList: []
    }
  },
  async created() {
    // 获取客户列表
    this.getClientList()
    // 获取经纪列表
    this.getAgentList()
    // 获取客户数量
    this.getClientNumber()
  },
  methods: {
    // 失焦重渲客户页面
    renderClientList() {
      this.getClientList()
      this.getClientNumber()
    },
    // 筛选功能
    search() {
      this.pageConfig._start = 0
      this.currentPage = 1
      this.getClientList()
      this.getClientNumber()
    },
    // 实现分页
    currentChange(newPage) {
      this.pageConfig._start = (newPage - 1) * this.pageConfig._limit
      this.getClientList()
    },
    // 获取客户数量
    async getClientNumber() {
      const res = await getClientNumber({
        name_contains: this.keyword || null,
        agent: this.selectAgent || null
      })
      this.total = res.data
    },
    // 获取客户列表
    async getClientList() {
      const res = await getClientList({
        ...this.pageConfig,
        name_contains: this.keyword || null,
        agent: this.selectAgent || null
      })
      this.clientList = res.data
    },
    // 获取经纪列表
    async getAgentList() {
      const res = await getAgentList({
        _start: 0,
        _limit: 999
      })
      this.agentList = res.data
    },
    // 添加客户按钮
    addFn() {
      this.showDialog = true
    },
    // 确认添加按钮
    async confirmFn() {
      if (!this.$refs.upload.fileList[0]) return this.$message.error('请先上传图片')
      if (this.$refs.upload.fileList[0].status !== 'success') return this.$message.error('请等待上传完毕')
      await this.$refs.form.validate()
      if (this.formData.id) {
        await updateClient({
          ...this.formData,
          image: this.$refs.upload.fileList[0].url
        })
      } else {
        await addClient({
          ...this.formData,
          image: this.$refs.upload.fileList[0].url
        })
      }
      this.$message.success('操作成功')
      this.closeFn()
      this.getClientList()
    },
    // 关闭弹窗
    closeFn() {
      this.formData = {
        agent: '',
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '',
        image: ''
      }
      this.$refs.form.resetFields()
      this.$refs.upload.fileList = []
      this.showDialog = false
    },
    // 删除客户
    delFn(id) {
      this.$confirm('是否确定删除？', '删除', {
        type: 'warning'
      }).then(async() => {
        await delClient(id)
        this.getClientList()
      }).catch(err => {
        console.log('取消：', err)
      })
    },
    // 编辑客户
    async editFn(id) {
      this.showDialog = true
      const res = await getClientById(id)
      this.formData = res.data
      this.$refs.upload.fileList = [{ url: this.formData.image }]
      console.log(177, this.formData)
    }
  }
}
</script>

<style>
.el-table{
  margin-top: 20px;
}
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
